package com.dada.utils;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@SuppressWarnings("rawtypes")
public abstract class JsonUtils {

	private static final Logger log = LoggerFactory.getLogger(JsonUtils.class);
	
	private static final ObjectMapper mapper = new ObjectMapper();
	private static final ObjectMapper mapperNonNull = new ObjectMapper();
	
	static {
		mapperNonNull.setSerializationInclusion(Include.NON_NULL);
		mapperNonNull.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	}
	
	public static String transformObjToJson(Object obj) throws Exception {
		return mapper.writeValueAsString(obj);
	}
	
	/** 转换一个对象为JSON, 若是属性值为NULL, 则去掉 */
	public static String transformObjToJsonNonNull(Object obj) {
		try {
			return mapperNonNull.writeValueAsString(obj);
		} catch (JsonProcessingException e) {
			log.error("transformObjToJsonNonNull error.", e);
			return null;
		}
	}
	
	public static <T> T transform(String jsonText, Class<T> clz) throws Exception {
		return mapper.readValue(jsonText, clz);
	}
	
	public static Map transformJsonToMap(String jsonText) throws Exception {
		return transform(jsonText, LinkedHashMap.class);
	}
	
	public static List transformJsonToList(String jsonText) throws Exception {
		return transform(jsonText, ArrayList.class);
	}
	
	public static Object transformJsonToObject(String jsonText) throws Exception {
		return transform(jsonText, Object.class);
	}
	
	/** transform json text to obj */
	public static Object transformJsonToObj(String jsonText) throws Exception {
		Object readedObj = null;
		
		if (jsonText.startsWith("{")) {
			readedObj = transformJsonToMap(jsonText);
		} else if (jsonText.startsWith("[")) {
			readedObj = transformJsonToList(jsonText);
		} else {
			readedObj = transformJsonToObject(jsonText);
		}
		return readedObj;
	}
	
	public static void main(String[] args) throws Exception {
		
	}
	
}
